import { VersionManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { Button, Card, Col, Divider, message, Row, Space, Tooltip } from 'antd';
import { useCallback, useContext, useMemo, useState } from 'react';
import { VersionDetailContext } from '../common/UpdateContext';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import {
  downloadTemplate,
  getColorTextLoadMap,
  getCompanyID,
  getPosIDs,
  getTenantID,
  getUserDepID,
  getUserID,
  splitFileUrl,
} from '@/utils';
import MyIcon from '@/components/MyIcon';
import cls from 'classnames';
import { VersionCheckModal } from './VersionCheckModal';
import { VersionCancelModal } from './VersionCancelModal';
import { VerticalRightOutlined } from '@ant-design/icons';
import { DirectlyIssueModal } from './DirectlyIssueModal';
export const DetailLeftView: React.FC<VersionManageAPI.IVersionDetailLeftView> = () => {
  const {
    prefixCls,
    curRes,
    getVersionDetailData,
    reloadVersionInfo,
  } = useContext(VersionDetailContext);

  /**入口是哪   true为详情 false为新增编辑 */
  // const [addOrDetailflag, setAddOrDetailflag] = useState<boolean>(true)

  /**直接签发开关 */
  const [directlyIssue, setDirectlyIssueModal] = useState<boolean>(false);

  /**
   * 处理文件显示
   */
  const fileList = useMemo(() => {
    let attachList: any[] = [];
    // attachList = splitFileUrl(getVersionDetailData?.attachUrl);
    attachList = splitFileUrl(getVersionDetailData?.versionUrl);
    return attachList;
  }, [getVersionDetailData]);

  /**
   * 返回文件名称处理
   * @param fileName 文件对象
   * @returns
   */
  const getFileNameNotType = (fileName: any) => {
    let arr: string[] = fileName?.split('.');
    let endType: any = arr?.pop();
    let nameStr: string = arr.join('');
    if (nameStr.length >= 6) {
      nameStr = nameStr.substr(0, 3) + '...' + nameStr.substr(-1);
    }
    return nameStr + `.${endType}`;
  };

  /**
   * 处理是否展示操作按钮框
   */
  const handleOperation = useMemo(() => {
    let isShowBtn: any = {
      allBtnDiv: false, //所有按钮
      issuedBtn: false, //直接签发
    };
    if (
      curRes?.['/versionController/issue'] &&
      (getVersionDetailData?.state == 0 ||
        getVersionDetailData?.state == 1 ||
        getVersionDetailData?.state == 2)
    ) {
      isShowBtn['issuedBtn'] = true;
      isShowBtn['allBtnDiv'] = true;
    }

    return isShowBtn;
  }, [curRes, getVersionDetailData]);

  /**
   * 保存监听的滚动条高度
   */
  const [scrollHeight, setScrollHeight] = useState<number>(0);
  const scrollHeightCallback = useCallback(
    (height: number) => {
      setScrollHeight(height);
    },
    [scrollHeight],
  );

  /**
   * 回到顶部
   */
  const backToTopFunc = (nodeId: string) => {
    let anchorElement = document.getElementById(nodeId);
    if (anchorElement) {
      anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  /**
   * 监听鼠标是否移入移出
   * true 移入    false 移出
   */
  const [hoverBackTop, setHoverBackTop] = useState<boolean>(false);

  /**
   * 监听 公告内容滚动
   * @param event
   */
  const monitorScrolling = (event: any) => {
    let { target } = event;
    if (target.scrollTop > document.body?.clientHeight * 0.3) {
      scrollHeightCallback(target?.scrollTop);
    }

    if (target?.scrollTop < document.body?.clientHeight * 0.3) {
      if (scrollHeight != 0) {
        scrollHeightCallback(0);
        setHoverBackTop(false);
      }
    }
  };

  /**
   * 处理版本状态颜色
   * @param versionState 传入的当前版本状态
   * @returns
   */
  const versionStateColor = (state: any) => {
    let versionStateColor: any = '';
    let versionState: any = '';
    if (state == 0) {
      versionState = '起草';
      versionStateColor = '#ff008c';
    }
    if (state == 1) {
      versionState = '待审核';
      versionStateColor = '#cc00ff';
    }
    if (state == 2) {
      versionState = '未通过';
      versionStateColor = '#ff0000';
    }
    if (state == 3) {
      versionState = '已通过';
      versionStateColor = '#22ff00';
    }
    if (state == 4) {
      versionState = '已作废';
      versionStateColor = '#940909';
    }
    return {
      versionState,
      versionStateColor,
    };
  };

  return (
    <div
      className={prefixCls + 'row-col-divBox'}
      style={{
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <Card
        title={'版本详情'}
        className={cls(
          pageStyles['page-view'],
          prefixCls + 'cardExtra',
          prefixCls + 'cardHead',
        )}
        bodyStyle={{ height: '90%', padding: '5px 0px' }}
        extra={
          getVersionDetailData?.isTop == 1 ? (
            <div className={prefixCls + 'cardExtra-iconIsTop'}>
              <MyIcon type="icon-zhiding" />
            </div>
          ) : (
            <></>
          )
        }
      >
        <Row className={'cardBodyRow'}>
          <Col span={24} className={'cardBodyCol'}>
            <div className={prefixCls + 'versionDetail'}>
              <Row
                style={{
                  padding: '0px 10px',
                  marginRight: 0,
                  marginLeft: 0,
                }}
                gutter={[10, 10]}
              >
                <Col span={20}>
                  <div className={prefixCls + 'versionDetail-title'}>
                    {getVersionDetailData && (
                      <>
                        【
                        {getVersionDetailData.versionType == '0'
                          ? '安卓端'
                          : getVersionDetailData.versionType == '1'
                          ? '苹果端'
                          : getVersionDetailData.versionType == '2'
                          ? '电脑端'
                          : '~~'}
                        】
                      </>
                    )}
                    当前版本：{getVersionDetailData?.publicNum?.toFixed(1)}
                  </div>
                  <div
                    className={prefixCls + 'versionDetail-content'}
                    style={{ fontSize: '14px' }}
                  >
                    创建时间：
                    <span style={{ color: '#545454' }}>
                      {getVersionDetailData?.createTime?.split(' ')?.[0] ??
                        '--'}
                    </span>
                    &nbsp;&nbsp;&nbsp;&nbsp; 发布时间：
                    <span style={{ color: '#545454' }}>
                      {getVersionDetailData?.signTime?.split(' ')?.[0] ?? '--'}
                    </span>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    {fileList &&
                      fileList.length > 0 &&
                      getVersionDetailData?.versionType != '2' && (
                        <>
                          应用下载：
                          <span style={{ color: '#545454' }}>
                            {fileList.map((e: any, i: any) => {
                              return (
                                <Col span={6} key={i}>
                                  <Tooltip title={e.attachName}>
                                    <a
                                      onClick={() => {
                                        message.success('下载中，请稍后...');
                                        downloadTemplate(
                                          '/versionController/downloadFile',
                                          e.attachName,
                                          e.attachUrl,
                                          () => {},
                                        );
                                      }}
                                    >
                                      {/* <MyIcon type="icon-file-text-fill" />
                                      &nbsp; */}
                                      {getFileNameNotType(e.attachName)}
                                    </a>
                                  </Tooltip>
                                </Col>
                              );
                            })}
                          </span>
                        </>
                      )}
                  </div>
                </Col>
                <Col
                  span={4}
                  className={prefixCls + 'versionDetail-titleRightCol'}
                >
                  <div
                    style={{
                      padding: '5px 10px',
                      border: '1px solid #e4e4e4',
                    }}
                  >
                    <MyIcon
                      type="icon-dian"
                      style={{
                        color: versionStateColor(getVersionDetailData?.state)
                          .versionStateColor,
                      }}
                    />
                    &nbsp;
                    <span
                      style={{
                        color: versionStateColor(getVersionDetailData?.state)
                          .versionStateColor,
                      }}
                    >
                      {
                        versionStateColor(getVersionDetailData?.state)
                          .versionState
                      }
                    </span>
                  </div>
                </Col>
              </Row>
              <Divider />
              <div
                style={{ height: document.body.clientHeight * 0.3 }}
                className={prefixCls + 'versionDetail-scrollBox'}
              >
                <ScrollBarLayout
                  style={{
                    padding: '5px 15px',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                  }}
                  onScroll={monitorScrolling}
                >
                  <Row id={'announceViewScroll'} style={{ height: 'auto' }}>
                    <Col span={24}>
                      <div
                        style={{ fontSize: '20px' }}
                        dangerouslySetInnerHTML={{
                          __html:
                            getVersionDetailData && getVersionDetailData?.id
                              ? getVersionDetailData?.upgradeNote?.contentHtml
                              : '',
                        }}
                        className={pageStyles['editorStyle']}
                      />
                    </Col>
                  </Row>
                  <div className={prefixCls + 'versionDetail-contentUser'}>
                    <div>
                      {getVersionDetailData?.state == 3 ? (
                        <>
                          <div style={{ display: 'flex' }}>
                            <div style={{ textAlign: 'right', width: '6em' }}>
                              发布人：
                            </div>
                            <span style={{ color: '#545454' }}>
                              {(getVersionDetailData &&
                                getVersionDetailData?.signerName) ||
                                '--'}
                            </span>
                          </div>
                          <div style={{ display: 'flex' }}>
                            <div style={{ textAlign: 'right', width: '6em' }}>
                              发布部门：
                            </div>
                            <span style={{ color: '#545454' }}>
                              {(getVersionDetailData &&
                                getVersionDetailData?.signDepartmentName) ||
                                '--'}
                            </span>
                          </div>
                          <div style={{ display: 'flex' }}>
                            <div style={{ textAlign: 'right', width: '6em' }}>
                              发布时间：
                            </div>
                            <span style={{ color: '#545454' }}>
                              {(getVersionDetailData &&
                                getVersionDetailData?.signTime) ||
                                '--'}
                            </span>
                          </div>
                        </>
                      ) : (
                        <>
                          <div style={{ display: 'flex' }}>
                            <div style={{ textAlign: 'right', width: '6em' }}>
                              创建人：
                            </div>
                            <span style={{ color: '#545454' }}>
                              {(getVersionDetailData &&
                                getVersionDetailData?.createrName) ||
                                '--'}
                            </span>
                          </div>
                          <div style={{ display: 'flex' }}>
                            <div style={{ textAlign: 'right', width: '6em' }}>
                              创建部门：
                            </div>
                            <span style={{ color: '#545454' }}>
                              {(getVersionDetailData &&
                                getVersionDetailData?.createDepartmentName) ||
                                '--'}
                            </span>
                          </div>
                          <div style={{ display: 'flex' }}>
                            <div style={{ textAlign: 'right', width: '6em' }}>
                              创建时间：
                            </div>
                            <span style={{ color: '#545454' }}>
                              {(getVersionDetailData &&
                                getVersionDetailData?.createTime) ||
                                '--'}
                            </span>
                          </div>
                        </>
                      )}
                    </div>
                  </div>
                </ScrollBarLayout>
              </div>
            </div>
            {handleOperation?.allBtnDiv && (
              <div className={'cardBodybtn'}>
                <Space>
                  {handleOperation?.issuedBtn && (
                    <Button
                      type={'primary'}
                      onClick={() => {
                        setDirectlyIssueModal(true);
                      }}
                    >
                      直接签发
                    </Button>
                  )}
                </Space>
              </div>
            )}
          </Col>
        </Row>
      </Card>

      {scrollHeight > document.body.clientHeight * 0.3 && (
        <>
          <div
            onMouseEnter={(e: any) => {
              e?.stopPropagation();
              setHoverBackTop(true);
            }}
            onMouseLeave={(e: any) => {
              e?.stopPropagation();
              setHoverBackTop(false);
            }}
            className={prefixCls + 'backTopStyle'}
            onClick={() => {
              backToTopFunc('announceViewScroll');
            }}
          >
            <div className={prefixCls + 'backTopStyle-circleDiv'}>
              {hoverBackTop ? (
                <>
                  <div>返回</div>
                  <div>顶部</div>
                </>
              ) : (
                <>
                  <VerticalRightOutlined />
                </>
              )}
            </div>
          </div>
        </>
      )}

      {/**直接签发 */}
      {directlyIssue && (
        <DirectlyIssueModal
          onClose={() => {
            setDirectlyIssueModal(false);
          }}
          isShowModal={directlyIssue}
          checkRows={getVersionDetailData}
          reloadVersion={() => {
            reloadVersionInfo();
          }}
        ></DirectlyIssueModal>
      )}
    </div>
  );
};
